// src/features/messages/api/use-create-member.ts
import {useCallback, useMemo, useState} from "react";
import {MARK_DATA_URL} from "@/lib/social/constants";
import {v4 as uuidv4} from 'uuid';
import {db} from "@/lib/db";
import {useCurrentMember} from "@/features/workspaces/api/use-current-member";
import toast from "react-hot-toast";
import {useRouter} from "next/navigation";

type Options = {
    onSuccess?: (workspaceId: string) => void
    onError?: (error: Error) => void
    onSettled?: () => void
    throwError?: boolean
}

type RequestType = {
    body: string
    workspaceId: string
    image?: string
    userId?: string
    // channelId?: string
    channelId?: string
    parentMessageId?: string
    conversationId?: string
} | null

type ResponseType = {
    id: string
} | null

// client
export const useCreateMessage = () => {
    // create db message
    const router = useRouter()

    const [data, setData] = useState<ResponseType>(null)
    const [error, setError] = useState<Error | null>(null)
    const [status, setStatus] =
        useState<"success" | "error" | "settled" | "pending" | null>()

    const isPending = useMemo(() => status === 'pending', [status])
    const isSuccess = useMemo(() => status === 'success', [status])
    const isSettled = useMemo(() => status === 'settled', [status])
    const isError = useMemo(() => status === 'error', [status])

    const mutate = useCallback(async (values: RequestType, options?: Options) => {
        const {data: member} = await useCurrentMember({
            workspaceId: values?.workspaceId!, userId: values?.userId
        })

        try {
            setData(null)
            setError(null)
            setStatus('pending')

            let m = {}
            if (values?.parentMessageId) {
                // const parentRes = await fetch(`${MARK_DATA_URL}/messages/${values?.parentMessageId}`)
                const parentRes = await fetch(`/api/messages/${values?.parentMessageId}`)
                const parent = await parentRes.json()
                console.log('parent', parent)

                m = {
                    parentMessageId: values?.parentMessageId,
                    // threadName: '', // cur member
                    threadCount: parent.threadCount ? parent.threadCount + 1 : 1,
                    threadImage: '',
                    threadTimestamp: new Date().getTime().toString(),
                    // threadTimestamp: new Date(),
                }
            }

            const id = uuidv4()
            let message = {
                ...values,
                userId: undefined,
                // userId: values?.userId,
                memberId: member.id,
                // createdAt: new Date().getTime(),
                // body: JSON.stringify(values!.body),
                ...m,
                parentMessageId: values?.parentMessageId || undefined,
                // id
            }
            console.log('new message: ', message)
            // create workspace
            // const res = await fetch(`${MARK_DATA_URL}/messages`, {
            const res = await fetch(`/api/messages`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(message),
            })

            if (res.ok) {
                setStatus('success')
                options?.onSuccess?.(id)
            }
            return message
        } catch (error) {
            setStatus('error')
            options?.onError?.(error as Error)
            if (options?.throwError) throw error
        } finally {
            setStatus("settled")
            toast.success(`发送成功`)
            options?.onSettled?.()
            // router.refresh()
            // window.location.reload()
        }
    }, []);

    return {
        mutate, error, isPending, isSuccess, isSettled, isError
    }
}